﻿using PremisPublisher.ViewModel;
using GalaSoft.MvvmLight.Messaging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using PremisPublisher.Messages;

namespace PremisPublisher
{
    /// <summary>
    /// Interaction logic for CryptDirectoryFilesWindow.xaml
    /// </summary>
    public partial class CryptDirectoryFilesWindow : Window
    {

        private CryptDirectoryFilesViewModel model;

        public CryptDirectoryFilesWindow()
        {
            InitializeComponent();

            model = this.DataContext as CryptDirectoryFilesViewModel;
            
            Messenger.Default.Register<ShowFolderChoosenMessage>(this, AddDirectory);
            Messenger.Default.Register<DelFolderChoosenMessage>(this, DelDirectory);

            Closed += CryptDirectoryFilesWindow_Closed;
        }

        void CryptDirectoryFilesWindow_Closed(object sender, EventArgs e)
        {
            Messenger.Default.Unregister<ShowFolderChoosenMessage>(this);
            Messenger.Default.Unregister<DelFolderChoosenMessage>(this);
        }


        private void DelDirectory(DelFolderChoosenMessage obj)
        {
            if (list_dirs.SelectedValue == null) return;

            var result = System.Windows.MessageBox.Show(obj.Message, "提示", MessageBoxButton.YesNo);

            if (result == MessageBoxResult.Yes)
            {
                var p = list_dirs.SelectedValue.ToString();
                if (model.ListDirectorys.Count(d => d.Equals(p)) > 0)
                    model.ListDirectorys.Remove(p);
            }
        }

        private void AddDirectory(ShowFolderChoosenMessage obj)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = obj.Message;
            dialog.ShowNewFolderButton = false;
            var result = dialog.ShowDialog();

            if (result == System.Windows.Forms.DialogResult.OK)
            {
                if (model.ListDirectorys.Count(d => d.Equals(dialog.SelectedPath)) == 0)
                    model.ListDirectorys.Add(dialog.SelectedPath);
            }
        }

        private void list_dirs_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                e.Effects = DragDropEffects.Link;
            else e.Effects = DragDropEffects.None;
        }

        private void list_dirs_Drop(object sender, DragEventArgs e)
        {
            string msg = "drop";

            if (e.Data.GetDataPresent(DataFormats.FileDrop))
            {
                msg = ((System.Array)e.Data.GetData(DataFormats.FileDrop)).GetValue(0).ToString();
                model.ListDirectorys.Add(msg);
            }
        }
    }
}
